<?php

class InputBuilder {

    public static $singleton;
    public $fieldsArray = array();
    public $db;
    public $sql;
    public $tableName;
    public $pkRecord;
    public $dsCombos;
    public $jsfunctions = array();
    public $widgetsManager;
    public $rootPath;
    public $debug = array();

    function saveNewField($field, $value, $pkRecord) {

        $this->db->query_insert('cllg_table_valuebyfield', array('PK_RECORD' => sqlValue($pkRecord, 'text'),
            'VALUE' => sqlValue(getParam($field), 'text'),
            'FK_TABLEFIELD' => sqlValue($field, 'text')));
    }

    function updateField($field, $value, $pkRecord) {
        $this->db->query_update('cllg_table_valuebyfield', array('VALUE' => sqlValue($value, 'text')), 'FK_TABLEFIELD=' . sqlValue($field, 'text') .
                ' AND PK_RECORD=' . sqlValue($pkRecord, 'text'));
    }

    function isGridTabType($tab) {
        $r = $this->db->queryToArray("select t.TIPO from cllg_table_tab t
		 			where t.ID=$tab and t.TABLE_NAME='$this->tableName'");
        $r = $r[0];
        return ($r["TIPO"] == 1);
    }

    function isGridFieldType($field) {
        $r = $this->db->queryToArray("select t.TIPO from cllg_table_tab t,cllg_tablefield f
		 			where f.NAME='$field' and f.FK_TAB=t.ID and f.TABLE_NAME='$this->tableName'");
        $r = $r[0];
        return ($r["TIPO"] == 1);
    }

    function saveFields($pkRecord) {
        $debug = array();
        $fields = $this->fieldsArray;
        //save none grid fields
        foreach ($fields as $fld) {
            if (!$this->isGridFieldType($fld)) {
                $r = getFieldValue($this->db, $this->tableName, $pkRecord, $fld);

                $a = getParam($fld);
                $v = getMultiselectValues($a);

                if (count($r) > 0) {
                    $this->updateField($fld, $v, $pkRecord);
                } else {
                    $this->saveNewField($fld, $v, $pkRecord);
                }
            }
        }

        $this->deleteGridFields($pkRecord);
        $debug = $this->saveGridFields($pkRecord);

        return print_r($debug, true);
    }

    function deleteGridFields($pk) {
        reset($_REQUEST);
        while ($arrGET = each($_REQUEST)) {
            $arrExplode = explode("-", $arrGET["key"]);
            if (isset($arrExplode[1])) {
                $this->db->query_delete('cllg_table_valuebyfield', sprintf("FK_TABLEFIELD =%s AND PK_RECORD=%s", sqlValue($arrExplode[0], 'text'), sqlValue($pk, 'text')));
            }
        }
    }

    function saveGridFields($pk) {
        $d = array();
        reset($_REQUEST);
        while ($arrGET = each($_REQUEST)) {
            $arrExplode = explode("-", $arrGET["key"]);
            if (isset($arrExplode[1])) {
                if (!isEmpty($arrGET["value"])) {
                    $data = array('PK_RECORD' =>
                        sqlValue($pk, 'text'),
                        'VALUE' => sqlValue($arrGET["value"], 'text'),
                        'FK_TABLEFIELD' => "'" . $arrExplode[0] . "'",
                        'CORRELATIVO' => "'" . $arrExplode[1] . "'");
                    $this->db->query_insert('cllg_table_valuebyfield', $data);
                    $d[] = $this->db->lastQuery;
                    $d[] = $data;
                }
            }
        }
        return $d;
    }

    function loadFields($tableName) {
        $this->db = DbManager::getMe();
        $this->tableName = $tableName;

        $order = "ORD,FK_TAB";
        $where = sprintf("TABLE_NAME=%s", sqlValue($tableName, 'text'));
        $where.=" AND STATUS=1";
        $rs = $this->db->query_select("cllg_tablefield", $where, $order);
        foreach ($rs as $row) {
            $field = $row["NAME"];
            $this->fieldsArray[] = $row["NAME"];
        }
    }

    function getRowColsGrid($tab) {
        $r = $this->db->queryToArray("select count(*) total from cllg_table_tab t,cllg_tablefield f
		 			where t.ID=$tab and f.FK_TAB=t.ID and f.TABLE_NAME='$this->tableName'");
        $r = $r[0];
        return ($r["total"]);
    }

    function buildGridTab($tab, $pk = 'NONE') {
        echo "";
        ?>
        <div style="width: 100%; float: left;">
            <table width="100%" cellpadding="2" cellspacing="2" border="0" id="tbl_<?php echo $tab; ?>">
                <?php
                $arrCampos = array();
                $strQuery = "SELECT  *
                                            FROM    cllg_tablefield 
                                            WHERE   cllg_tablefield.TABLE_NAME = '$this->tableName' 
                                            AND     cllg_tablefield.FK_TAB = '{$tab}' 
                                            AND     cllg_tablefield.STATUS = '1' 
                                            ORDER   BY cllg_tablefield.ORD";
                $qTMP = $this->db->queryToArray($strQuery);
                $intNumRows = $this->db->num_rows;
                $intColumnas = $intNumRows;
                $sinWidth = 95 / $intNumRows;
                $intCorrelativo = 0;
                if ($intNumRows > 0) {
                    ?>         <thead>
                        <tr>
                            <th style="width: 5%; text-align: center; border-bottom: 1px solid black;"><b>Corr.</b></th>
                            <?php
                            foreach ($qTMP as $rTMP) {
                                $arrCampos[$rTMP["NAME"]] = $rTMP;
                                ?>
                                <th style="width: <?php print $sinWidth; ?>%;text-align: center; border-bottom: 1px solid black;">
                                    <b><?php print $rTMP["CAPTION"]; ?></b>
                                </th>
                                <?php
                            }
                            ?>
                        </tr></thead><tbody>
                        <?php
                    }
                    $strQuery = "SELECT  *
                                            FROM    cllg_tablefield,
                                                    cllg_table_valuebyfield 
                                            WHERE   cllg_tablefield.TABLE_NAME = '$this->tableName'
                                            AND     cllg_tablefield.FK_TAB = '{$tab}'
                                            AND     cllg_tablefield.STATUS = '1'
                                            AND     cllg_table_valuebyfield.PK_RECORD = '{$pk}'
                                            AND     cllg_tablefield.NAME = cllg_table_valuebyfield.FK_TABLEFIELD
                                            ORDER   BY cllg_table_valuebyfield.CORRELATIVO, cllg_tablefield.ORD";
                    $qTMP = $this->db->queryToArray($strQuery);
                    $intNumRows = $this->db->num_rows;
                    $intCorrelativo = 0;
                    $intContador = 0;
                    if ($intNumRows > 0) {
                        foreach ($qTMP as $rTMP) {
                            $intContador++;
                            if ($intCorrelativo == 10) {
                                break;
                            }
                            if ($intContador == 1) {
                                $intCorrelativo++;
                                ?>
                                <tr>
                                    <td style="width: 5%; text-align: center"><?php print $intCorrelativo; ?></td>
                                    <?php
                                }
                                ?>
                                <td style="text-align: center;">
                                    <input type="text"
                                           id="<?php print $rTMP["NAME"]; ?>-<?php print $intCorrelativo; ?>"
                                           name="<?php print $rTMP["NAME"]; ?>-<?php print $intCorrelativo; ?>"
                                           value="<?php print $rTMP["VALUE"]; ?>" style="width: 80%;">
                                </td>
                                <?php
                                if ($intContador == $intColumnas) {
                                    ?>
                                </tr>
                                <?php
                                $intContador = 0;
                            }
                        }
                    }

                    $rows = $intNumRows > 0 ? ($intNumRows / $intColumnas) : 0;

                    for ($i = 1; $i <= (10 - $rows); $i++) {
                        $intCorrelativo++;
                        ?>
                        <tr>
                            <td style="width: 5%; text-align: center"><?php print $intCorrelativo; ?></td>
                            <?php
                            foreach ($arrCampos as $k => $v) {
                                ?>
                                <td style="width: <?php print $sinWidth . "%"; ?>;text-align: center;">
                                    <input type="text"
                                           id="<?php print $k; ?>-<?php print $intCorrelativo; ?>"
                                           name="<?php print $k; ?>-<?php print $intCorrelativo; ?>" value="" style="width: 80%;">
                                </td>
                                <?php
                            }
                            ?>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
            </table>

        </div>

        <?php
    }

    function buildGridField($row, $fill = false) {
        switch ($row['CONTROL_TYPE']) {
            case 'textbox':
                return $this->buildInput($row, $fill);
            case 'checkbox':
                return $this->buildCheck($row, $fill);
            case 'select':
                return $this->buildComboBox($row, $fill, $row["FK_CATALOG"]);
            case 'txarea':
                return $this->buildTxArea($row, $fill);
        }
        return "";
    }

    function build($tableName, $pkRecord = NULL, $tab = NULL) {
        $this->tableName = $tableName;

        if (!$this->isGridTabType($tab)) {

            $fill = ($pkRecord == NULL ? false : true);
            $rs = array();
            $order = "ORD,FK_TAB";
            $where = sprintf("TABLE_NAME='%s'", $tableName);
            $where.=" AND STATUS=1";
            if ($tab != NULL) {
                $where.=sprintf(" AND FK_TAB=%s ", $tab);
            }

            $rs = $this->db->query_select("cllg_tablefield", $where, $order);

            foreach ($rs as $row) {
                $row['PK_RECORD'] = $pkRecord;
                switch ($row['CONTROL_TYPE']) {
                    case 'textbox':
                        $this->buildFormField($row['CAPTION'], $this->buildInput($row, $fill));
                        break;
                    case 'checkbox':
                        $this->buildFormField($row['CAPTION'], $this->buildCheck($row, $fill));
                        break;
                    case 'select':
                        $this->buildFormField($row['CAPTION'], $this->buildComboBox($row, $fill, $row["FK_CATALOG"]));
                        break;
                    case 'txarea':
                        $this->buildFormField($row['CAPTION'], $this->buildTxArea($row, $fill));
                        break;
                    case 'sep':
                        $this->buildSeparator();
                        break;
                }
            }
        } else {
            $this->buildGridTab($tab, $pkRecord);
        }
    }

    function buildInput($row, $filled = false) {
        $value = "";
        if ($filled) {
            if (!isset($row["VALUE"])) {
                $result = $this->getFieldValue($this->db, $this->tableName, $row['PK_RECORD'], $row['NAME']);
                $result = count($result) > 0 ? $result[0] :
                        array("NAME" => "", "LONG" => "", "VALUE" => "");
                $value = $result["VALUE"];
            }else{
                $value = $row["VALUE"];
            }
        }

        $input = ' <input name="' . $row['NAME'] . '" maxlength="' . $row['LONG']
                . '" size="' . $row['LONG']
                . '" id="' . $row['NAME']
                . '" value="' . $value . '" type="text" />';

        return array("input" => $input, "id" => $row["NAME"]);
    }

    function buildCheck($row, $filled = false) {
        $result = $this->getFieldValue($this->db, $this->tableName, $row['PK_RECORD'], $row['NAME']);
        $result = count($result) > 0 ? $result[0] :
                array("NAME" => "", "LONG" => "", "VALUE" => "");
        $input = '<input name="' . $row['NAME']
                . '" id="' . $row['NAME'] . '" value="1" type="checkbox" ' .
                (($filled == true && $result["VALUE"] == "1") ? 'checked="checked" ' : '') . '/>';

        return array("input" => $input, "id" => $row["NAME"]);
    }

    function buildTxArea($row, $filled = false, $catalog = null) {
        $result = $this->getFieldValue($this->db, $this->tableName, $row['PK_RECORD'], $row['NAME']);
        $result = count($result) > 0 ? $result[0] :
                array("NAME" => "", "LONG" => "", "VALUE" => "");
        $input = ' <textarea name="' . $row['NAME'] . '" rows="5" cols="50" id="' . $row['NAME']
                . '" size="" >' . ($filled == true ? $result["VALUE"] : "") . '</textarea>';
        return array("input" => $input, "id" => $row["NAME"]);
    }

    function buildComboBox($row, $filled = false, $catalog = null) {
        $input = '<select name="' . $row['NAME'] . '" size="1" id="' . $row['NAME'] . '">';
        echo "<!--$filled,$catalog-->";
        if (!$filled && $catalog == null) {
            $input.='<option value="">vacio</option> ';
        } else {
            $defVals = array();
            if ($catalog != null) {
                $defVals = $this->db->queryToArray("select * from cllg_util_catalog_value where FK_CATALOG=$catalog", true);
                echo "<!--" . print_r($defVals, true) . " -->";
                $defVals = $this->db->queryToArray("select * from cllg_util_catalog_value where FK_CATALOG=$catalog", false);
                echo "<!--" . print_r($defVals, true) . " -->";
            }
            $result = $this->getFieldValue($this->db, $this->tableName, $row['PK_RECORD'], $row['NAME']);
            $result = count($result) > 0 ? $result[0] :
                    array("NAME" => "", "LONG" => "", "VALUE" => "");
            $result = $result["VALUE"];
            $result = $result != null ? explode(",", $result) : array();
            $selected = 'selected="selected"';
            foreach ($defVals as $i) {
                $s = "";
                foreach ($result as $v) {
                    if ($i["VALUE"] == trim($v)) {
                        $s = $selected;
                        break;
                    }
                }
                $val = htmlentities($i["VALUE"]);
                $lab = htmlentities($i["LABEL"]);
                $input.="<option $s value='$val'>$lab</option> ";
            }
        }
        $input.='</select>';
        return array("input" => $input, "id" => $row["NAME"]);
    }

    function buildFormField($label, $input) {
        echo '<div>';
        echo '<label for="' . $input['id'] . '">' . $label . '</label>';
        echo $input['input'];
        echo '</div>';
    }

    function buildSeparator() {
        echo '<hr/>';
    }

    function getFieldValue($db, $tableName, $pkRecord, $fieldName) {
        $sql = "SELECT A.NAME,B.VALUE FROM cllg_tablefield A LEFT JOIN
            cllg_table_valuebyfield B ";
        $sql.=sprintf("ON (A.NAME=B.FK_TABLEFIELD AND B.PK_RECORD='%s') ", $pkRecord);
        $sql.=sprintf("WHERE B.FK_TABLEFIELD='%s' ", $fieldName);
        $sql.=sprintf("AND A.TABLE_NAME='%s' ", $tableName);

        $rs = $db->queryToArray($sql);
        return $rs;
    }

}
?>